var userAgent = navigator.userAgent.toLowerCase();
var is_opera = userAgent.indexOf('opera') != -1 && opera.version(); var is_ie = (userAgent.indexOf('msie') != -1 && !is_opera) && userAgent.substr(userAgent.indexOf('msie') + 5, 3);
//验证码
function seccode(id)
{
	var img = 'seccode.php?rand='+Math.random();

	id = id || 'img_seccode';
	document.writeln('<img id="' + id + '" src="'+img+'" align="absmiddle">');
}

//更新验证码
function updateseccode(id)
{
	var img = 'seccode.php?rand='+Math.random();

	id = id || 'img_seccode';
	if($('#' + id))
	{
		$('#' + id).attr('src', img);
	}
}

function isUndefined(variable) 
{
	return typeof variable == 'undefined' ? true : false;
}
/*中文字长度*/
function strLen(str) 
{
	var charset = typeof document.charset != 'undefined' ? document.charset : document.characterSet; 
	var len = 0;
	for(var i = 0; i < str.length; i++) 
	{
		len += str.charCodeAt(i) < 0 || str.charCodeAt(i) > 255 ? (charset.toLowerCase() == "utf-8" ? 3 : 2) : 1;
	}
	return len;
}

function bindVip() 
{
	var matches;
	var id, ids = [];
	var users = $('.ppl_username');
	var pattern = /my\.php\?ac=space&uid=(\d+).*$/;
	var ft;

	$.each(users, function(i, item) {
		if (matches = pattern.exec(item.href))
			ids.push(parseInt(matches[1]));
		else
			ids.push(0);
	});
		
	if (!ids.length)
		return;	

	ids = ids.join('-');
	$.get('fr.php', {ac: 'vip', ids: ids}, function(data) {
		var vImg;
		var myVip;
		var vPic = '';
		//var imgPath = cdnUrl + 'image/';
		var imgPath = 'image/img/vip/';

		if (!data)
			return;
		if (typeof frTips == 'undefined')
			return;

		ft = eval('(' + frTips + ')');
		data = data.split('-');

		$.each(data, function(i, item) {
			var tmpImg;

			// maybe level
			item = parseInt(item);
			if (item == 0) 
				return true;

			vPic = ft[1][item];
			if (!vImg)
				vImg = new Image();

			$(vImg).attr('src', imgPath + vPic);
			tmpImg = $(vImg).clone();
			if ($.trim($(users[i]).text()).length == 0)
				$(tmpImg).addClass('user-mark');

			$(users[i]).append(tmpImg);	
		});
	});
}

$(document).ready(function() {
	//更换背景判断
	if(screen.width>=1200){
		if($("#my_game_active").hasClass("b_atHome")){
			$(".imageHeadBackground").addClass("imageHeadBackgroundIndex")	
		}else{
			$(".imageHeadBackground").addClass("imageHeadBackgroundOther")	
		}
	}

	// feedback
	$('#feedback').click(function() {
		feedback();
	});

	bindVip();
		
	$('#addbookmark').click(function(){
		var title="皮皮鲁Z社区, WWW.PPL419.COM";
		var url="http://WWW.PPL419.COM";
		if (window.sidebar){
			window.sidebar.addPanel(title,url,"");
		 }
		else if(document.all){
			window.external.AddFavorite(url,title);
		 }
		else if(window.opera && window.print){
			return true;
		 }
	});

	$(".badge .item").hover(function() {
		$(".tip_box",$(this)).show();
	}).mouseout(function() {
		$(".tip_box",$(this)).hide();
	});
});

function feedback()
{
	var html = '';
	html += '<div class="box_main feedback">';
	html += '<form action="" onsubmit="return postFeedback(this);">';
	html += '<ul>';
	html += '<li>';
	html += '<span class="title">所属应用：</span>';
	html += '<select class="value" id="fb_app" name="fb_app">';
	html += '<option value="1">登录/注册/个人帐号</option>';			
	html += '<option value="2">邀请</option>';
	html += '<option value="3">徽章</option>';			
	html += '<option value="4">红塔乐园</option>';
	html += '<option value="5">Z星球日记</option>';			
	html += '<option value="6">好友</option>';		
	html += '<option value="7">道具</option>';			
	html += '<option value="8">特别邮票</option>';
	html += '<option value="9">家长总动员</option>';			
	html += '<option value="10">白客</option>';	
	html += '<option value="11">419宗罪</option>';

	html += '<option value="12">其他</option>';		
	html += '</select>';
	html += '</li>';
	html += '<li>';
	html += '<span class="title">求助类型：</span>';
	html += '<select class="value" name="fb_type">';
	html += '<option value="1">疑问</option>';
	html += '<option value="2">建议</option>';
	html += '<option value="3">BUG/纠错</option>';
	html += '<option value="4">不良内容及恶意骚扰</option>';
	html += '<option value="5">其他</option>';
	html += '</select>';
	html += '</li>';
	html += '<li>';
	html += '<span class="title">求助详情：</span>';
	html += '<textarea rows="" cols="" class="value feedback_content" name="fb_body"></textarea>';
	html += '</li>';
	html += '</ul>';
	html += '<p class="submit"><input type="submit" value="意见反馈" class="button04"/></p>';
	html += '</form>';
	html += '</div>';
	$('select').hide();
	PPL419.popup.showDialog('', html, 'pop_up_box01');	
}

function postFeedback(obj)
{
	var fb_app = obj.fb_app.value;
	var fb_type = obj.fb_type.value;
	var fb_body = obj.fb_body.value;

	if (fb_body.length > 200)
	{
		PPL419.popup.secondShow('反馈内容不能超过200字, <a href="javascript:PPL419.popup.resetDia();">返回重填</a>');
		$('.confirm_button').unbind('click').click(function() {
			PPL419.popup.resetDia();
		});
		return false;
	}

	$.post('do.php?do=feedback', {fb_app: fb_app, fb_type: fb_type, fb_body: fb_body}, function(data) {
		var msg = '';

		if (data == 1)		
			msg = '<p style="text-align:center;">感谢你的反馈</p>';
		else if (data == 2)
			msg = '<p style="text-align:center;">所填数据不能为空, <a href="javascript:PPL419.popup.resetDia();">返回重填</a></p>';
		else if (data == 3)
			msg = '<p style="text-align:center;">数据库错误，请联系管理员</p>';
		else
			msg = '<p style="text-align:center;">请先登录</p>';

		PPL419.popup.secondShow(msg + '  ');
		$('.confirm_button').unbind('click').click(function() {
			data == 2 ? PPL419.popup.resetDia() : PPL419.popup.hideDialog();		
		});
			
	});

	return false;
}


function showReport(id, formhash, type)
{
	var body = '';

	body += '<div class="alert-box-report alert-modules-wrap">';
	body += '	<h5>举报不良信息<em>（请放心，您的隐私会得到保护）</em></h5>';
	body += '	<div class="alert-content-report">';
	body += '		<p class="report-more-description">您可以填写更多举报说明</p>';
	body += '		<p><textarea name="reason" id="report_reason">是色情、暴力、还是广告？</textarea></p>';
	body += '		<p><input type="button" class="btn btn-sure" value="确定" onclick="reportSubmit(' + id + ',\'' + formhash + '\',' + type + ');" /><input type="button" class="btn btn-cancel" value="取消" onclick="PPL419.popup.hideDialog();" /></p>';
	body += '	</div>';
	body += '</div>';

	PPL419.popup.showDialog(body);
	$('#report_reason').one('click', function() {
		$(this).val('');	
	});
}
function reportSubmit(bid, formhash, type)
{
	var reason = $('#report_reason').val();
	if(reason.length <= 0 || reason == '是色情、暴力、还是广告？')
	{
		alert('字数范围: 1 - 300');
		$('#report_reason').val('').focus();
		return false;
	}
	else if (reason.length > 300)
	{
		alert('字数范围: 1 - 300');
		return false;
	}

	$.post('earth.php?ac=blog&do=report','reason='+reason+',&bid='+bid+'&formhash='+formhash+'&type='+type+'&reportsubmit=true',function(data){
		data = PPL419.popup.reciveJson(data,1);
		if(data != 0){
		//	PPL419.popup.showDialog('感谢您参与监督与举报，我们将及时处理');
			popWin.success('感谢您参与监督与举报，我们将及时处理');
		}
	});
}

var msgNotify = {
	_timeout: 300000,
	
	get: function() {
		$.getJSON('pm.php?ac=chkmsg&r=' + Math.round(Math.random() * 1000), function(data) {
			var nums = 0;
			var ac = '';

			if (data) {
				if (data['msg']) {
					//PPL419.popup.showDialog('与服务器失去连接，请重新登录');
					//PPL419.popup.showDialog(data['msg']);
					//PPL419.popup.forward('index.php');
					return;
				}

				if (data['notice']) {
					nums += data['notice'];
					ac = 'notice';
				}
				if (data['system']) {
					nums += data['system'];
					ac = 'system';
				}
				if (data['person']) {
					nums += data['person'];
					ac = '';
				}

				if (nums) {
					$('.mail-number').text(nums).removeClass('close-box');		
					if (ac)
						$('.messageBox').attr('href', 'pm.php?ac=' + ac);
				}
			}

			setTimeout(msgNotify.get, msgNotify._timeout);
		});
	}
};

/*提示登录*/
function showLogin()
{
//	PPL419.popup.showJump('您还未登录，请先登录');
		var showMsg = '您还未登录，请先登录';
		var url = 'index.php';
		PPL419.popup.showJump(showMsg, url, function() {
				setTimeout(function(){window.location.href = url;}, sec);
		});
	//PPL419.popup.forward('index.php');
}

//每日摇奖
function dayAward()
{
	var dayAwardCookie = getCookie('PPL419.popup.ayAward' + getCookie('PPL419.popup.oginuser'));
	//if(dayAwardCookie)
	//	PPL419.popup.showDialog('非常抱歉，神奇罐头每天最多只能打开两次。');
	//else
//	{
		//请求后台赠送
		$.get('/do.php?do=dayaward&r='+Math.random(), function(data){
			var cg, r, msg, suc;

			suc = function(gold, isf) {
				var html = '', msg;

				if (isf)
					msg = '两个小时后，还有一次打开神奇罐头的机会哦！';
				else
					msg = '今天的两次机会已经用完了，明天再来吧！';

				html += '<div class="layout1-container">';
				html += '	<div class="magic-box-pop">';
				html += '		<h5>神奇罐头</h5>';
				html += '		<div class="magic-box-content">';
				html += '			<span class="magic-box-img"></span>';
				html += '			<p>从神奇罐头获得<span class="icon global-gold-icon">' + gold + '</span><br />' + msg + '</p>';
				html += '			<input type="button" value="确定" class="btn btn-sure" onclick="javascript:PPL419.popup.hideDialog();" /><br />';
				html += '		</div>';
				html += '	</div>';
				html += '</div>';

				PPL419.popup.showDialog(html);
			};

 			r = PPL419.popup.reciveJson(data,1);
			if (r > 0) {
				cg = parseInt($('#topgold').text());
				$('#topgold').text(cg + r);

				if (dayAwardCookie < 1)
					suc(r, 1);
				else
					suc(r, 0);
			} else if(r < 0){
				//var msg = ';
				if (dayAwardCookie == 1)
					PPL419.popup.showWarn('非常抱歉，神奇罐头每天最多只能打开两次。');
				else
					PPL419.popup.showWarn('对不起，距离你上次打开神奇罐头的时间还不到两个小时，请稍候再来。');
			}
		});
//	}
}

/**
 * 取得cookie
 * 
 * @param cName $cName 
 * @access public
 * @return void
 */
function getCookie(cName)
{
	var r = '';
	var cookieLen = document.cookie.length;
	if(cookieLen > 0)
	{
		cStart = parseInt(document.cookie.indexOf(cName + "="));
		cStartLen = parseInt(cName.length + 1);
		if(cStart != -1)
		{
			cStart += parseInt(cStartLen);
			cEnd = document.cookie.indexOf(";", cStart);
			if(cEnd == -1) cEnd = cookieLen;
			r = document.cookie.substring(cStart, cEnd);
		}
	}

	return r;
}

function showMyFriends()
{
	var gid = -1, html= '';
	var isHide = $('#friendList').length;

	if (!isHide) {
		html += '<div id="friendList">';
		html += '	<div class="chooseGroupHolder">';
		html += '		<select onchange="getMyFriends(this.value)">';
		html += '			<option value="-1">全部好友</option>';
		html += '			<option value="0">不分组</option>';
		html += '			<option value="1">同学</option>';
		html += '			<option value="2">朋友</option>';
		html += '			<option value="3">亲人</option>';
		html += '		</select>';
		html += '	</div>';
		html += '	<ul>';
		html += '	</ul>';
		html += '	<input type="hidden" name="flist" id="flist" value="">';
		html += '	<div style="width:100%;text-align:center;">';
		html += '		<a href="javascript:void(0);"  class="button01" onclick="selectMyFriend();">确定</a>';
		html += '	</div>';
		html += '</div>';
				
		$('.selectArea').after(html);
		$('#friend_selected').attr('readonly', 'readonly');
		getMyFriends(-1);
	}

	$('#friendList').toggle();
}

function getMyFriends(gid)
{
	//gid = gid || -1;
	$.getJSON('fr.php?ac=fl', {gid: gid, r: Math.random()}, function(data) {
		var html = '';

		if (data.error)	
			return;
		$.each(data, function(i, item) {
			html += '<li><input name="fid" type="radio" value="' + item[0] + '_' + item[1] + '" id="fid' + i + '" /><label for="fid' + i + '" title="Z星球居民ID:'+item[0]+'">' + item[1] + '</label></li>';
		});
		if (html == '')
			html = '<li>分组无好友</li>';

		$('#friendList ul').html(html);
	});
}

function selectMyFriend()
{
	var fid = $('input[@name=fid][checked]').val();			

	if (fid) {
		fid = fid.split('_');
		$('#friend_selected').val(fid[1]);	
		$('#flist').val(fid[0]);	
	} else {
		$('#friend_selected').val('');	
		$('#flist').val(0);	
	}

	$('#friendList').hide();
}


(function(){	
	var mp = window.mp=function(miniData,parent){
		this.init(miniData,parent);
		return this;
	};
	mp.fn = mp.prototype = {
		init:function (miniData,parent){
			miniData=$.extend({
				showDelay:null,
				closeDelya:null,
				delayTime:500
			},miniData);
			$.extend(this,miniData);
			this.bindMpDocument(parent);
		},
		bindMpDocument:function (parent){
			this.mpMouseover(this,parent);
			this.mpMouseout(this,parent);
		},
		mpMouseover:function (_p,parent){
			$(parent).find("."+this.mpStartClass).unbind("mouseover").bind("mouseover",function (){
				var _this = this;
				_p.showDelay = setTimeout(function() {_p.insertDocument($(_this).attr("miniData"), _this,_p);}, _p.delayTime);
			});	
		},
		mpMouseout:function (_p,parent){
			$(parent).find("."+this.mpStartClass).unbind("mouseout").bind("mouseout", function() {
				_p.closeMp(_p)
			});	
		},
		buildDom:function (obj){
			var html = '';
			html = '<div class="profileCardBubble" id="profileCardBubble">';
			html += '	<span class="profileCardArrow"></span>';
			html += '	<div class="profileCardContent clearfix">';
			html += '   	<a href="my.php?ac=space&uid=' + obj.uid + '&f=mp" title="查看' + obj.tname + '的个人资料" class="profileCardPhoto"><img alt="查看' + obj.tname + '的个人资料" src="' + obj.headPic + '" /></a>';
			html += '       <div class="profileCardInfo clearfix">';
			html += '       	<p class="profileCardName"><a href="my.php?ac=space&uid=' + obj.uid + '&f=mp" title="查看' + obj.tname + '的个人资料">' + obj.tname + '</a></p>';
			html += '           <ul>';
			html += '           	<li><a href="earth.php?ac=blog&do=listuser&uid=' + obj.uid + '&f=mp">TA的日记</a></li>';
			html += '           	<li><a href="tw.php?ac=my&uid=' + obj.uid + '&f=mp">TA的白客</a></li>';
			html += '           	<li><a href="album.php?uid=' + obj.uid + '&f=mp">TA的相册</a></li>';
			html += '           	<li><a href="my.php?ac=badges&uid=' + obj.uid + '&f=mp">TA的徽章</a></li>';
			html += '           	<li><a href="my.php?ac=group&uid=' + obj.uid + '&f=mp">TA的Z星群</a></li>';
			html += '           </ul>';
			html += '       </div>';
			html += '   </div>';
			html += '</div>';
			return html;
		},
		friendOrMessage:function (isFriend,obj){
			var friendOrMessage= isFriend?'<a href="javascript:void(0);" onclick="friend.showPopAddAsk(\'' + obj.uid + '_' + obj.tname + '\');" class="addFriend">加好友</a>':'<a href="javascript:void(0);" onclick="pm.show_reply(' + obj.uid + ', \'' + obj.tname + '\');" class="sendMsg">发消息</a>';
			return friendOrMessage;
			
		},
		insertDocument:function (obj,p,_p){
			var obj = eval('(' + obj + ')');
			if(obj.uid==userid){return}
			var mpDom = this.buildDom(obj);
			$("body").remove(".profileCardBubble").append(mpDom);
			this.insertFriendOpreat(this,obj);
			this.setPosition(p,_p);
			this.bindPopMouse(_p);
		},
		insertFriendOpreat:function (_p,obj){
			$.get('fr.php?ac=isfriend', {fid:obj.uid}, function(data) {
				switch(data){
					case "0":
						$(".profileCardBubble .profileCardName").append(_p.friendOrMessage(true,obj));
						break;
					case "1":
						$(".profileCardBubble .profileCardName").append(_p.friendOrMessage(false,obj));
						break;
					case "-1":
						break;
				}
			})
		},
		setPosition:function (p,_p){
			$(".profileCardBubble").css("left",$(p).offset().left).css("top",$(p).offset().top+$(p).height()+7)
		},
		bindPopMouse:function (_p){
			$(".profileCardBubble").bind("mouseover",function (){
				_p.stopClosing();
			}).bind("mouseout",function (){
				_p.closeMp(_p);
			})
		},
		closeMp:function (_p){
			if(this.showDelay){
				clearTimeout(this.showDelay);
				this.showDelay = null;
			}
			if( $('.profileCardBubble').css('display') == 'block'){
				this.closeDelya = setTimeout(function(){
					_p.closeMpNow();
				},this.delayTime);
			}	
		},
		stopClosing:function (){
			if(this.closeDelya){
				clearTimeout(this.closeDelya);
				this.closeDelya = null;
			}
		},
		closeMpNow:function (){
			this.clearDocument();
		},
		clearDocument:function (){
			$("body").find(".profileCardBubble").remove()
		}
	}
})()
$(document).ready(function (){
	var commonMp = window.commonMp = new mp({mpStartClass:"needMiniProfile"},$(document));

	msgNotify.get();
})

var popWin = {
	iscfm: 0,

	bw: function(msg, cs, callback) {
		var html = '';
		cs = cs || 'alert-warning';

		html += '<div class="alert-box-small alert-modules-wrap">';
		html += '	<h5>系统提示</h5>';
		html += '	<div class="alert-content">';
		html += '		<p class="alert-system">&nbsp;<br />';
		html += '			<div style="padding-left: 36px;"><span class="alert-bg ' + cs + '"></span>' + msg + '</div><br />';
		html += '		</p>';
		html += '		<p class="alert-system">';
		html += '			<input type="button" value="确定" onclick="PPL419.popup.hideDialog()"  id="bw_but" class="btn btn-sure" />';
		if (this.iscfm)
			html += '			<input type="button" value="取消" onclick="PPL419.popup.hideDialog()" class="btn btn-cancel" />';
		html += '			<br />';
		html += '			&nbsp;</p>';
		html += '	</div>';
		html += '</div>';

		PPL419.popup.showDialog(html);
		if (callback)
			$('#bw_but').unbind('click').click(callback);
	},

	success: function (msg, cb) {
		if (!cb)
			PPL419.popup.showSuccess(msg);
		else
			this.bw(msg, 'alert-success', cb);	
	},

	warn: function(msg, cb) {
		if (!cb)
			PPL419.popup.showWarn(msg);
		else
			this.bw(msg, 'alert-warning', cb);	
	},

	error: function(msg, cb) {
		popWin.warn(msg, cb);
	},
		   
	cfm: function(msg, cb) {
		PPL419.popup.showAsk(msg, cb);
	}
};


//高亮显示当前链接元素[现在还得基于Jquery]
var highLightCurrentLink    = function(findDom, currentClass, level) {
    var modeFileExp = '';
    var fileType    = '';
    var otherParam  = null;
    var modeFlag    = 0;
    var sameMode    = {thread: "group"};
    var otherMode   = {my: "ac", tw: "ac", apps: "app", faq: "ct"};
    var sameOtherParam  = {my: {match: "ac=picture", param: "my.php?ac=profile"}};
    
    var url         = window.location.href;
    
    var nowHref     = url.substring(url.lastIndexOf('/') + 1);//拿到当前访问的页面及查询内容
    if(typeof nowHref == 'undefined' || nowHref == '') {
        return true;
    }
    
    var nowPage     = nowHref.substring(0, nowHref.indexOf('.')); //拿到当前的访问页面，不要.php
    for(element in sameMode) {
        if(nowPage == element) {
            nowPage     = sameMode[element];
            break;
        }
    }
    //拿到其它的模式
    for(var item in otherMode) {
       if(nowPage == item) {
         modeFlag       = 1;
         var oMode  = new RegExp(otherMode[item] + "=(\\w+)" , "gi");
         otherParam     = nowHref.match(oMode);  //拿到其它的决定变量
         if(otherParam) {
            otherParam  = otherParam[0];
            var paramFlag   = 0;
            for(var page in sameOtherParam) {
                if(nowPage == page && otherParam == sameOtherParam[page].match){
                    paramFlag   = 1;
                    otherParam  = null;
                    nowHref     = sameOtherParam[page].param;
                }
            }
            if(paramFlag == 0) {
                //otherParam  = new RegExp(otherParam, 'gi');
            }
         }
         break;
       }
    }
    var maskLoc     =  nowHref.indexOf('?');
    if(maskLoc != -1) {
        fileType    = nowHref.substring(nowHref.indexOf('.'), maskLoc);
    } else {
        fileType    = nowHref.substring(nowHref.indexOf('.'));
    }
    //modeFileExp        = new RegExp(nowPage + '\\' + fileType, 'gi');
    modeFileExp        = nowPage + fileType;
    

    if(typeof level == 'undefined') {
        level = 0;
    }
    $(findDom).each(function() {
        var curHref     = $(this).children('a').attr('href');
        if(typeof curHref != 'undefined' && curHref != '') {
            if(curHref.match(modeFileExp) != null) {
                if(modeFlag == 1) {
                    if(otherParam == null && curHref != nowHref) {
                        return true;
                        
                    } else if(otherParam != null && curHref.match(otherParam) == null) {
                        return true;
                    }
                }
                var targetDom = $(this);
                if(level < 0) {
                    for(var i = 0; i > level; i --) {
                       targetDom    = $(targetDom).children('a'); 
                    }
                } else if(level > 0) {
                    for(var i = 0; i < level; i ++) {
                       targetDom    = $(targetDom).parent(); 
                    }
                }
                $(targetDom).addClass(currentClass);

                return false;
            }
        }
    });
};

//限制字数信息存储容器
var verifyLenInfo   = {defMaxLen: 158};
/**
 * 绑定字符长度检测
 * 
 * @param string contentDomId 输入区域ID
 * @param string showDomId 显示区域ID
 * @param int maxLen 最大长度 默认 158
 * @return void
 */
var bindLenVerify = function(contentDomId, showDomId, maxLen) {
    if(typeof maxLen == 'undefined') {
        maxLen  = verifyLenInfo.defMaxLen;
    }
    verifyLenInfo[contentDomId]  = {len: maxLen, show: showDomId};
    $('#' + contentDomId).bind('change keyup', function() {
        XTools.checkValidWords(this.id, verifyLenInfo[this.id].show, verifyLenInfo[this.id].len);
    });
    $('#' + contentDomId).change();
};
